package com.gitee.loyo;


import io.vertx.core.Future;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Iterator;

public class Bridges {

    public static boolean contains(String domain) {
        return BridgeConfig.INSTANCE.bridges.stream().filter(bridge -> bridge.domain.equals(domain)).count() > 0;
    }

    public static Bridge get(String domain){
        return BridgeConfig.INSTANCE.bridges.stream().filter(bridge -> bridge.domain.equals(domain)).findFirst().get();
    }

    private static void remove(String domain){
        Iterator<Bridges.Bridge> ite = BridgeConfig.INSTANCE.bridges.iterator();
        while (ite.hasNext()){
            Bridges.Bridge bridge = ite.next();
            if (bridge.domain.equals(domain)){
                ite.remove();
                return;
            }
        }
    }

    public static Future<Void> add(Bridge bridge) {
        synchronized(BridgeConfig.INSTANCE){
            if(contains(bridge.domain)){
                return Future.failedFuture("domain name is existed");
            }
            BridgeConfig.INSTANCE.bridges.add(bridge);
            return BridgeConfig.INSTANCE.save();
        }
    }

    public static Future<Void> update(Bridge bridge) {
        synchronized(BridgeConfig.INSTANCE){
            Bridges.Bridge record = get(bridge.domain);
            if(record == null){
                return Future.failedFuture("domain name is not existed");
            }
            record.hostname = bridge.hostname;
            return BridgeConfig.INSTANCE.save();
        }
    }

    public static Future<Void> remove(Bridge bridge) {
        synchronized(BridgeConfig.INSTANCE){
            remove(bridge.domain);
            return BridgeConfig.INSTANCE.save();
        }
    }

    public static class Bridge{
        public String domain;
        public String hostname;

        public String base64(){
            return Base64.getUrlEncoder().encodeToString(domain.getBytes(StandardCharsets.UTF_8));
        }

        public String getDomain() {
            return domain;
        }

        public String getHostname() {
            return hostname;
        }
    }
}
